package com.gz.purchase.library.util;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * @author 陈希然
 *
 */
public class SingtonAsyncHttpClient extends AsyncHttpClient {

	private static Lock mLock = new ReentrantLock();
	private static SingtonAsyncHttpClient mInstance;
	
	private SingtonAsyncHttpClient() {
		super(80);
		setURLEncodingEnabled(false);
	}
	
	public static SingtonAsyncHttpClient getInstance(){
		if(mInstance == null){
    		mLock.lock();
    		try{
				if(mInstance == null){
					mInstance = new SingtonAsyncHttpClient();
				}
    		}finally{
    			mLock.unlock();
    		}
    	}
    	
    	return mInstance;
	}

    /**
     * Sets an optional CookieStore to use when making requests
     * @param cookieStore The CookieStore implementation to use, usually an instance of {@link PersistentCookieStore}
     */
    public void setCookieStore(CookieStore cookieStore) {
    	
    	if(cookieStore == null)
    		return ;
        //httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    	//由于PHP收不到httpclient的cookie，只能将值放到消息头里面
    	List<Cookie> cookies = cookieStore.getCookies();
    	if(cookies.size() > 0){
    		Cookie cookie = cookies.get(cookies.size()-1);
    		//Cookie cookie = cookies.get(0);
    		//String[] array = TextUtils.split(cookie.getValue(), ";");
    		addHeader("Cookie", "access_token="+cookie.getValue());
    	}
    }

}
